package com.hsd.znsh.listener;

import com.hsd.znsh.repository.*;
import com.hsd.znsh.service.LoraService;
import com.hsd.znsh.service.PushService;
import com.hsd.znsh.vlc.VlcListenerThread;
import org.hibernate.SessionFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.concurrent.ExecutorService;

@WebListener
public class ServletListener implements ServletContextListener {

    private VlcListenerThread vlcListenerThread;

    private SensorListenerThread sensorListenerThread;

    private GatewayListenerThread gatewayListenerThread;

    private ControlListenerThread controlListenerThread;

    private ExecutorService executorService;
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        WebApplicationContext applicationContext=WebApplicationContextUtils.getWebApplicationContext(servletContext);
        vlcListenerThread=new VlcListenerThread(servletContext);
        vlcListenerThread.start();

        SensorRepository sensorRepository=applicationContext.getBean(SensorRepository.class);
        ControlRepository controlRepository=applicationContext.getBean(ControlRepository.class);
        HostRepository hostRepository=applicationContext.getBean(HostRepository.class);
        EventRepository eventRepository=applicationContext.getBean(EventRepository.class);
        PushService pushService=applicationContext.getBean(PushService.class);
        LoraService loraService=applicationContext.getBean(LoraService.class);
        executorService=applicationContext.getBean(ExecutorService.class);

        sensorListenerThread=new SensorListenerThread(sensorRepository,hostRepository,eventRepository,pushService);
        sensorListenerThread.start();

        controlListenerThread=new ControlListenerThread(controlRepository,hostRepository,
                eventRepository,pushService,loraService);
        controlListenerThread.start();

        GatewayRepository gatewayRepository=applicationContext.getBean(GatewayRepository.class);
        gatewayListenerThread=new GatewayListenerThread(gatewayRepository,hostRepository,eventRepository,pushService,loraService);
        gatewayListenerThread.start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        vlcListenerThread.flag=false;
        sensorListenerThread.flag=false;
        gatewayListenerThread.flag=false;
        controlListenerThread.flag=false;
        executorService.shutdownNow();
    }
}
